package com.zzh.lib.views.listener;


import android.annotation.SuppressLint;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;

/**
 * Created by ZZH on 2022/11/22.
 *
 * @Date: 2022/11/22
 * @Email: zzh_hz@126.com
 * @QQ: 1299234582
 * @Author: zzh
 * @Description: 双击事件监听，单击事件监听
 */
public class HContinueClickListener implements View.OnTouchListener {

    private static final int timeout = 400;//双击间四百毫秒延时
    private int clickCount = 0;//记录连续点击次数
    private final Handler handler;
    private final MyClickCallBack myClickCallBack;

    public interface MyClickCallBack {

        void oneClick();//点击一次的回调

        void doubleClick();//连续点击两次的回调
    }

    public HContinueClickListener(MyClickCallBack myClickCallBack) {
        this.myClickCallBack = myClickCallBack;
        handler = new Handler();
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            clickCount++;
            handler.postDelayed(() -> {
                if (clickCount == 1) {
                    myClickCallBack.oneClick();
                } else {
                    myClickCallBack.doubleClick();
                }
                //清空handler延时，并防内存泄漏
                handler.removeCallbacksAndMessages(null);

                clickCount = 0;//计数清零
            }, timeout);//延时timeout后执行run方法中的代码
        }
        return consumeTouchEvent();//让点击事件继续传播，方便再给View添加其他事件监听
    }

    public boolean consumeTouchEvent() {
        return false;
    }

}
